package com.landinfo.web.rest;

import com.codahale.metrics.annotation.Timed;
import com.landinfo.service.TaskManagementService;
import com.landinfo.web.rest.util.HeaderUtil;
import com.landinfo.service.dto.TaskManagementDTO;
import com.zaxxer.hikari.HikariDataSource;
import io.github.jhipster.web.util.ResponseUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * REST controller for managing TaskManagement.
 */
@RestController
@RequestMapping("/api")
public class TaskManagementResource {

    private final Logger log = LoggerFactory.getLogger(TaskManagementResource.class);

    private static final String ENTITY_NAME = "taskManagement";

    private final TaskManagementService taskManagementService;

    //    @Resource
//    private SessionFactory sessionFactory;
    //
//    @PersistenceContext
//    @Autowired
//    private EntityManager entityManager;

    @Autowired
    private HikariDataSource hikariDataSource;


    public TaskManagementResource(TaskManagementService taskManagementService) {
        this.taskManagementService = taskManagementService;


    }

    /**
     * POST  /task-managements : Create a new taskManagement.
     *
     * @param taskManagementDTO the taskManagementDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new taskManagementDTO, or with status 400 (Bad Request) if the taskManagement has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/task-managements")
    @Timed
    public ResponseEntity<TaskManagementDTO> createTaskManagement(@Valid @RequestBody TaskManagementDTO taskManagementDTO) throws URISyntaxException {
        log.debug("REST request to save TaskManagement : {}", taskManagementDTO);
        if (taskManagementDTO.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new taskManagement cannot already have an ID")).body(null);
        }
        TaskManagementDTO result = taskManagementService.save(taskManagementDTO);
        return ResponseEntity.created(new URI("/api/task-managements/" + result.getId()))
                .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
                .body(result);
    }

    /**
     * PUT  /task-managements : Updates an existing taskManagement.
     *
     * @param taskManagementDTO the taskManagementDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated taskManagementDTO,
     * or with status 400 (Bad Request) if the taskManagementDTO is not valid,
     * or with status 500 (Internal Server Error) if the taskManagementDTO couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/task-managements")
    @Timed
    public ResponseEntity<TaskManagementDTO> updateTaskManagement(@Valid @RequestBody TaskManagementDTO taskManagementDTO) throws URISyntaxException {
        log.debug("REST request to update TaskManagement : {}", taskManagementDTO);
        if (taskManagementDTO.getId() == null) {
            return createTaskManagement(taskManagementDTO);
        }
        TaskManagementDTO result = taskManagementService.save(taskManagementDTO);
        return ResponseEntity.ok()
                .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, taskManagementDTO.getId().toString()))
                .body(result);
    }

    /**
     * GET  /task-managements : get all the taskManagements.
     *
     * @return the ResponseEntity with status 200 (OK) and the list of taskManagements in body
     */

    @GetMapping("/task-managements")
    @Timed
    public List<TaskManagementDTO> getAllTaskManagements() {
        log.debug("REST request to get all TaskManagements");
//        this.test();
//        this.test2();
        return taskManagementService.findAll();
    }

    private String test2() {
        Configuration configuration = new Configuration();
        configuration.configure();
        configuration.addResource("config/mapping/DefaultTemplate.hbm.xml");


        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

        Session s = sessionFactory.openSession();
        Object o = s.get("User", new Integer(1400));

        String result = o.toString();
        return result;
    }

    private void test() {
        //test1
        // Create the SessionFactory from hibernate.cfg.xml
        Configuration configuration = new Configuration();
        configuration.configure();
        configuration.addResource("config/mapping/DefaultTemplate.hbm.xml");


        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        Map david = new HashMap();
        david.put("name", "David");
        // Create an organization
//        Map foobar = new HashMap();
//        foobar.put("name", "Foobar Inc.");
        // Link both
//        david.put("organization", foobar);
        // Save both
        Session s = sessionFactory.openSession();
        Transaction tx = s.beginTransaction();
        s.save("User", david);
        //s.save("Organization", foobar);
        tx.commit();
        s.close();

    }

    /**
     * GET  /task-managements/:id : get the "id" taskManagement.
     *
     * @param id the id of the taskManagementDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the taskManagementDTO, or with status 404 (Not Found)
     */
    @GetMapping("/task-managements/{id}")
    @Timed
    public ResponseEntity<TaskManagementDTO> getTaskManagement(@PathVariable Long id) {
        log.debug("REST request to get TaskManagement : {}", id);
        TaskManagementDTO taskManagementDTO = taskManagementService.findOne(id);
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(taskManagementDTO));
    }

    /**
     * DELETE  /task-managements/:id : delete the "id" taskManagement.
     *
     * @param id the id of the taskManagementDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/task-managements/{id}")
    @Timed
    public ResponseEntity<Void> deleteTaskManagement(@PathVariable Long id) {
        log.debug("REST request to delete TaskManagement : {}", id);
        taskManagementService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

//    @PostConstruct
//    public void registerListeners() {
//        SessionFactory sessionFactory = null;
//        try {
//            entityManager.getTransaction().begin();
//            sessionFactory = entityManager.unwrap(SessionFactory.class);
//        } catch (Exception ex) {
//            ex.printStackTrace();
//
//
//        }
//    }

}
